package controller;

import db.BagDAO;
import model.Bag;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.NoSuchElementException;


public class BagServlet extends HttpServlet {

    private static Logger logger = Logger.getLogger(BagServlet.class);

    public void init() {
        logger.info("BagServlet started");
    }

    public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        res.setContentType("text/html");

        BagDAO BagDAO = new BagDAO();

        if (req.getParameter("id") != null && req.getParameter("action") == null) {
            int id = Integer.parseInt(req.getParameter("id"));
            try {
                Bag b = BagDAO.findById(id);
                if (b == null) {
                    throw new NoSuchElementException();
                }
                req.setAttribute("result", b);
                getServletConfig().getServletContext().getRequestDispatcher("/edit.jsp").forward(req, res);
            } catch (Exception e) {
                logger.info("No bag with id: " + id + " found.");
                getServletConfig().getServletContext().getRequestDispatcher("/error.jsp").forward(req, res);
            }
        } else if (req.getParameter("action") != null) {
            int id = Integer.parseInt(req.getParameter("id"));
            String type = req.getParameter("type");
            String price = req.getParameter("price");
            BagValidator v = new BagValidator();
            Map<String, String> errors = v.validate(type, price);
            Bag b = new Bag(id, type, price);
            if (errors.size() > 0) {
                errors.put("general_error", "Error occurred when saving");
                req.setAttribute("result", b);
                req.setAttribute("errors", errors);
                getServletConfig().getServletContext().getRequestDispatcher("/edit.jsp").forward(req, res);
            } else {
                BagDAO.update(b);
                res.sendRedirect("/Bag/s");
            }

        } else {
            ArrayList<Bag> bg = BagDAO.findAll();
            req.setAttribute("resultAll", bg);
            getServletConfig().getServletContext().getRequestDispatcher("/list.jsp").forward(req, res);
        }


    }

    public String getServletInfo() {
        return "BagServlet";
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {

        doGet(request, response);
    }
}
